<template>
    <!-- 待签订合同 -->
    <div class="signedContract padding-page ps-a workers">
        <div class="body_header">
            <el-button type="text">{{projectName}}</el-button>
            <div>
                <el-button type="primary" @click="batchSignContractStart">批量签署合同</el-button>
                <el-button type="primary" @click="cancelList">查看已驳回合同</el-button>
            </div>
        </div>

        <el-table border :data="tableData" style="width: 100%"  @selection-change="handleSelectionChange" height="80%">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
                prop="contractId"
                label="合同编号"
                width="180">
            </el-table-column>
            <el-table-column
                prop="partyBName"
                label="姓名"
                width="80">
            </el-table-column>
            <el-table-column
                prop="detailsTimeInfo.createTime"
                width="180"
                label="发起时间">
            </el-table-column>
            <el-table-column
                min-width="120"
                prop="contractStatus"
                label="状态">
                <template slot-scope="scope">
                    <el-button type="text">{{stateList[scope.row.contractStatus].label}}</el-button>
                </template>
            </el-table-column>
            <el-table-column
                width="100"
                prop="detailsTimeInfo.termValidityStart"
                label="合同生效日">
            </el-table-column>
            <el-table-column
                width="100"
                prop="detailsTimeInfo.termValidityEnd"
                label="合同终止日">
            </el-table-column>
            <el-table-column
                min-width="200"
                prop="detailsInfo.workingAddress"
                label="工作地点">
            </el-table-column>
            <el-table-column
                width="80"
                prop="detailsInfo.jobType"
                label="工种">
            </el-table-column>
            <el-table-column
                width="100"
                prop="detailsInfo.duty"
                label="职责">
            </el-table-column>
            <el-table-column
                min-width="100"
                prop="detailsInfo.paymentDate"
                label="报酬付款日">
            </el-table-column>
            <el-table-column
                width="120"
                prop="detailsInfo.workingSystemInfo"
                label="工时制度">
            </el-table-column>
            <el-table-column
                width="100"
                prop="detailsInfo.basicDailyWage"
                label="基本工资">
            </el-table-column>
            <el-table-column
                width="100"
                prop="detailsInfo.performanceSettlementType"
                label="绩效结算">
                <template slot-scope="scope">
                    <el-button type="text">{{performanceList[scope.row.detailsInfo.performanceSettlementType]}}</el-button>
                </template>
            </el-table-column>
            <el-table-column
                prop="detailsInfo.supplementaryMatters"
                label="补充事项">
            </el-table-column>
            <el-table-column
                width="210"
                label="操作">
                <template slot-scope="scope">
                    <el-button type="text" @click="showDetails(scope.row)">查看详情</el-button>
                    <el-button type="text" size="mini" @click="signed(scope.row.contractId)">签署</el-button>
                    <el-button type="text" size="mini" @click="rejected(scope.row.contractId)">驳回</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="m-t-20 d-flex ju-sb">
            <div>
                <!-- <el-button type="primary" size="mini" @click="signed">签署</el-button>
                <el-button type="danger" size="mini" @click="rejected">驳回</el-button> -->
            </div>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <router-view />

                <!-- 合同预览 -->
        <cDetails v-if="detailsShow" :pdfUrl="pdfUrl">
            <template>
                <div style="flex: 1;">
                    <span>
                        工人: {{detailsForm.originatorName}}
                    </span>
                    <span>
                        合同编号: {{detailsForm.contractId}}
                    </span>
                </div>
                <div>
                    <el-button @click="cal">返回</el-button>
                </div>
            </template>
        </cDetails>

        <el-dialog title="手机验证" :visible.sync="phoneVisible" width="500px" :modal-append-to-body='false'>
            <el-form :model="phoneForm" label-width="80px">
                <el-form-item label="手机号">
                    <el-input v-model="phoneForm.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="验证码">
                    <div style="display: flex">
                        <el-input v-model="phoneForm.verification" autocomplete="off" class="m-r-20"></el-input>
                        <el-button @click="getCode" :disabled="smsBtnDisabled">{{smsCodeText}}</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="phoneVisible = false">取 消</el-button>
                <el-button type="primary" @click="phoneSend()">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 批量签署使用 -->
        <el-dialog title="身份验证" :visible.sync="phoneVisibleV2" width="500px" :modal-append-to-body='false'>
            <el-form :model="phoneFormV2" label-width="80px">
                <el-form-item label="手机号">
                    <el-input v-model="phoneFormV2.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="验证码">
                    <div style="display: flex">
                        <el-input v-model="phoneFormV2.verification" autocomplete="off" class="m-r-20"></el-input>
                        <el-button @click="getCodeV2" :disabled="smsBtnDisabledV2">{{smsCodeTextV2}}</el-button>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="phoneVisibleV2 = false">取 消</el-button>
                <el-button type="primary" @click="phoneSendV2()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import cDetails from "../../../components/details";
import { mapGetters } from 'vuex'
import {
    QueryProjectSignContractDetailedInfoList,
    CancelContract,
    QueryContractFileDetails,
    getVerCodeV1,
    signElectronicContract,
    signMultipleElectronicContract,
    vaildSMS
} from '@/api/contract/workers'
export default {
    components: { cDetails },
    computed: {
        ...mapGetters([
            'userId',
            'currId',
            'roleId'
        ])
    },
    data() {
        return {
            tableData: [],
            stateList: [
                {label: '双方待签订', color: '#F56C6C'},
                {label: '甲方待签订', color: '#409EFF'},
                {label: '乙方待签订', color: '#909399'},
                {label: '合同生效', color: '#67C23A'},
                {label: '已取消', color: '#909399'},
                {label: '已驳回', color: '#67C23A'},
                {label: '已过期', color: '#67C23A'}
            ],

            performanceList: ['无绩效', '按量结算', '按天结算'],
            multipleSelection : [],  // 存放表格多选数据
            currentPage: 1,   // 当前页
            pageSize: 10,     //每页多少条
            total: 0,          // 总数量
            multipleSelectionIds: [],
            detailsShow: false,
            detailsForm: {},
            pdfUrl: '',
            phoneForm: {
                phone: '',
                verification: '',
                contractId: ''
            },
            phoneFormV2: {
                phone: '',
                verification: '',
                contractIds: []
            },
            phoneVisible: false,
            phoneVisibleV2: false,
            smsCodeText: '获取验证码',
            smsCodeTextV2: '获取验证码',
            smsBtnDisabled: false,
            smsBtnDisabledV2: false
        }
    },
    methods: {
        // 表格多选触发
        handleSelectionChange(val) {
            // console.log(val);
            this.multipleSelection = val;
            console.log("Hello:" + val.contractId);
            this.multipleSelectionIds = val.contractId;
        },
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.pageSize = val;
            this.currentPage = 1
            this.init()
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.currentPage = val
            this.init()
        },
        // 查看已驳回合同
        cancelList() {
			console.log(this.$route.query,'点击后' );
            this.$router.push({ path: '/workersCancelList', query: this.$route.query })
        },
        // 合同取消
        cancel() {
            this.detailsShow = false;
        },
        init() {
            const { projectId, projectName} = this.$route.query
            const data = {
                userId: this.userId,
                roleId: this.roleId,
                currId: this.currId,
                projectId,
                contractStatus: -1,
                projectName,
                pageFlag: 1,         //是否启用分页
                currentPage: this.currentPage,      //当前页
                queryNumber: this.pageSize
            }
            QueryProjectSignContractDetailedInfoList(data).then(res => {
                console.log(res)
                if(res.code == '0') {
                    this.tableData = res.data.result
                    this.total = res.data.resultTotal
                }
            })
        },
        // 驳回合同
        rejected(id) {
            console.log(this.multipleSelection)
            const params = {
                userId: this.userId,
//              roleId: this.roleId,
//              currId: this.currId,
                contractId: id
            }
            CancelContract(params).then(res => {
                if(res.code == '0') {
                    this.$message.success('操作成功')
                    // this.init()
                    this.$router.go(-1);
                }
            })
        },
        // 签署合同
        signed(id) {
            this.phoneForm= {
                phone: '',
                verification: '',
                contractId: id
            },
            // this.phoneForm.contractId = id
            this.phoneVisible = true
        },
        // 关闭
        cal() {
            this.detailsShow = false;
        },
        // 查看详情
        showDetails(row) {
            console.log('查看详情',row);
            this.detailsForm = row;
            const data = {
				contractId: row.contractId
			}
            QueryContractFileDetails(data).then(res => {
                console.log(res)
                if(res.code == '0') {
//                  this.detailsShow = true;
//                  this.pdfUrl = res.data.downloadUrl
						if (res.data.result[0].detailsUrlInfo.contractUrl != null) {
							this.detailsShow = true;
							this.pdfUrl = res.data.result[0].detailsUrlInfo.contractUrl.replace(
								"https://gymspic1.oss-cn-shanghai.aliyuncs.com", "");
						} else {
							this.$message.info('contractUrl为空');
						}
                }
            })
        },
        // 获取验证码
        getCode() {
            this.smsBtnDisabled = true;
            if(!this.phoneForm.phone) {
                this.smsBtnDisabled = false;
                return this.$message.warning('请输入手机号!')
            }
            const params = {
                oemType: 1,
                phone: this.phoneForm.phone
            };
            let secCount = 60;
            var timeCount = setInterval(() => {
                if (secCount > 0) {
                --secCount;
                this.smsCodeText = secCount + 's后重新获取'
                } else {
                window.clearInterval(timeCount);
                this.smsCodeText = '重新获取';
                this.smsBtnDisabled = false
                }
            }, 1000);
            getVerCodeV1(params).then(res => {
                if(res.respCode === '1') {
                    return this.$message.success('短信验证码发送成功!');
                }
            }).catch(error => {
                window.clearInterval(timeCount);
                this.smsCodeText = '重新获取';
                this.smsBtnDisabled = false;
                return this.$message.error('短信验证码发送失败');
            })
        },
        // 获取验证码
        getCodeV2() {
            this.smsBtnDisabledV2 = true;
            if(!this.phoneFormV2.phone) {
                this.smsBtnDisabledV2 = false;
                return this.$message.warning('请输入手机号!')
            }
            const params = {
                oemType: 1,
                phone: this.phoneFormV2.phone
            };
            let secCount = 60;
            var timeCount = setInterval(() => {
                if (secCount > 0) {
                    --secCount;
                    this.smsCodeTextV2 = secCount + 's后重新获取'
                } else {
                    window.clearInterval(timeCount);
                    this.smsCodeTextV2 = '重新获取';
                    this.smsBtnDisabledV2 = false
                }
            }, 1000);
            getVerCodeV1(params).then(res => {
                if(res.respCode === '1') {
                    return this.$message.success('短信验证码发送成功!');
                }
            }).catch(error => {
                window.clearInterval(timeCount);
                this.smsCodeTextV2 = '重新获取';
                this.smsBtnDisabledV2 = false;
                return this.$message.error('短信验证码发送失败');
            })
        },
        // 验证验证码
        phoneSend() {
            if (!this.phoneForm.verification) {
                return this.$message.warning('请输入验证码')
            }
            const params = {
                phone: this.phoneForm.phone,
                code: this.phoneForm.verification,
            };
            vaildSMS(params).then(res => {
                console.log(res, '验证码验证')
                if(res.respCode === '1') {
                    this.SEC()
                } else {
                    return this.$message.error(res.respMsg)

                }
            })
        },
        // 验证验证码
        phoneSendV2() {
            if (!this.phoneFormV2.verification) {
                return this.$message.warning('请输入验证码')
            }
            const params = {
                phone: this.phoneFormV2.phone,
                code: this.phoneFormV2.verification,
            };
            vaildSMS(params).then(res => {
                if(res.respCode === '1') {
                    this.batchSignContract()
                } else {
                    return this.$message.error(res.respMsg)
                }
            })
        },
        // 发起签署
        SEC() {
            const params = {
              
 				contractId: this.phoneForm.contractId,
                originatorType: 0,
                currId: this.currId,
                roleId: this.roleId,
                phone: this.phoneForm.phone,
                signCode: this.phoneForm.verification,
            };
            signElectronicContract(params).then(res => {
                console.log(res, '发起签署');
                if(res.code == '0'){
                    this.$message.success('操作成功')
                    this.phoneVisible = false
                    this.$router.push({path: '/workers'});
                }
            })
        },
        // 批量签署开始
        batchSignContractStart() {
            if (this.multipleSelection.length <= 0) {
                return this.$message.warning('请至少选择一项合同作为批量签署源');
            }
            let str = "";
            this.multipleSelection.forEach(item => {
                str += item.contractId + ",";
            });
            str = str.substring(0, str.length - 1);
            this.multipleSelectionIds = str.split(",");
            console.log(this.multipleSelectionIds);
            this.phoneVisibleV2 = true;
        },
        // 批量签署
        batchSignContract() {
            const param = {
                 contractIds: this.multipleSelectionIds,
                phone: this.phoneFormV2.phone,
                signCode: this.phoneForm.verification,
                currId: this.currId,
                roleId: this.roleId,
                contractType: 0,
                sourceType:10,
            };
            signMultipleElectronicContract(param).then(res => {
                console.log(res);
               if (res.code === 0) {
                    this.$message.success("签署合同总数: " + res.data.total + "\r\n成功签署数: " + res.data.success);
                   this.phoneVisibleV2 = false;
                   this.$router.push({path: '/workers'});
               }
            });
        }
    },
    created() {
        this.projectName = this.$route.query.projectName
        this.init()
    }
}
</script>
<style lang="scss">
    .signedContract {
        background: #fff;
        z-index: 12;
    }
    .body_header {
        display: flex; justify-content: space-between;
        padding-bottom: 10px;
        border-bottom: 1px solid #d8dce5;
    }
    .pagination {
        width: 100%;
    }
</style>
